<?php

namespace app\admin\controller\wanlshop;

use app\common\controller\Backend;
use app\common\model\Distribution;
use app\common\model\user\LevelOrder;
use think\exception\DbException;
use think\response\Json;

/**
 * 会员卡分佣订单管理
 *
 * @icon fa fa-circle-o
 */
class Membership extends Backend
{

    /**
     * 模型对象
     * @var \app\common\model\team\Level
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new LevelOrder();
    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(["distribution"=>function($query){
                    $query->where(["type"=>1]);
                },'user'])
                ->join("(select DISTINCT order_id from fhb_distribution where type=1) a","a.order_id=level_order.id")
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {
               /* $model_order = model('app\api\model\wanlshop\Order');
                $order=$model_order->field("id")->where(["level_order_id"=>$row["id"]])->find();
                $row->order_id=$order["id"]??0;*/
                $row["level_details"]=json_decode($row["level_details"],true);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 详情
     */
    public function detail($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row["distribution"]=Distribution::where(["order_id"=>$row["id"],"type"=>1])->with("commissuser")->select();
        if( !empty( $row["level_details"])){
            $row["level_details"]=json_decode($row["level_details"],true);
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
